<script setup>
    import { ref, onMounted, inject } from 'vue'
    import { Notification } from "@arco-design/web-vue";
    const { deviceIds, selectedDeviceIds }  = inject('devices')
    const selectLoading = ref(false)

    /**
     * 读取设备列表
     *
     * @returns Promise<void> 无返回值，异步执行
     */
    const readDevices = async () => {
        // loading
        selectLoading.value = true
        // 异步获取设备ID列表
        deviceIds.value = await window.xapi.getDeviceIds()
        // 过滤已选择的设备ID，过滤掉已经断连的设备不再显示
        //selectedDeviceIds.value = selectedDeviceIds.value.filter(deviceId => deviceIds.value.includes(deviceId))
        // 全选新读取出来的设备，上一行应该就没必要了
        selectedDeviceIds.value = deviceIds.value
        // 延迟操作，防止UI抖动
        setTimeout(() => {
            // 结束loading
            selectLoading.value = false
            // 获取设备列表的长度
            const length = deviceIds.value.length;
            // 根据设备数量判断通知类型
            const notiType = length === 0 ? 'warning' : 'success'
            // 构造通知消息
            const msg = 'devices connected：' + length
            // 显示通知
            Notification.info({
                title: 'notification',
                content: msg,
                type: notiType,
                duration: 2500,
            })
        }, 500);
    }

    const valueChange = (value) => {
        selectedDeviceIds.value = value
    }

    onMounted(() => {
        readDevices()
    })
</script>

<template>
  <div class="parent" style="display: flex; align-items: center">
    <a-select multiple
      allow-clear
      :model-value="selectedDeviceIds"
      :bordered=false
      :disabled="selectLoading"
      :max-tag-count=2
      :style="{flex: 1,height:'30px'}"
      @change="valueChange"
      placeholder="Please select device ...">
      <a-option v-for="device in deviceIds"
        :key="device"
        class="device-item"
        :tag-props="{color:'green'}">{{device}}</a-option>
      <template #empty>
        <a-empty description="No device connected!"/>
      </template>
    </a-select>
    
    <a-button shape="circle"
      class="btn"
      status="success"
      type="text"
      @click="readDevices">
      <icon-sync class="icon-sync" :spin="selectLoading" :style="{width:'20px',height:'20px'}"/>
    </a-button>
  </div>
</template>

<style scoped>
.parent {
    margin-top: 3px;
}
.btn {
  margin-left: 10px
}
.btn:focus {
  outline: none !important;
  box-shadow: none !important;
  border: none !important;
}
</style>